import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:xrenovation/routes.dart';
import 'package:xrenovation/services/locale_service.dart';
import 'package:xrenovation/utils/storage.dart';

class Http {
  // baseUrl末尾不要带斜杠
  static final baseUrl = 'https://api-test.xrenovation.ai';

  static final Dio _dio = Dio(
    BaseOptions(baseUrl: baseUrl, connectTimeout: const Duration(seconds: 30)),
  );

  static late final GlobalKey<NavigatorState> _navigatorKey;

  static Future<Response> delete(String path, dynamic data) async {
    return _dio.delete(path, data: data);
  }

  static Future<Response> get(String path) async {
    return _dio.get(path);
  }

  static void init({required GlobalKey<NavigatorState> navigatorKey}) {
    _navigatorKey = navigatorKey;

    // 添加拦截器
    _dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) async {
          // 添加语言头
          final locale = LocaleService().locale.languageCode;
          options.headers['Accept-Language'] = locale;
          // 自动添加token
          final token = await Storage.getToken();
          if (token != null) {
            options.headers['satoken'] = token;
          }

          return handler.next(options);
        },
        onResponse: (response, handler) async {
          // 打印响应信息
          debugPrint('┌────────────────────── Response ──────────────────────');
          debugPrint('│ URI: ${response.requestOptions.uri}');
          debugPrint('│ Response Data: ${response.data}');
          debugPrint('└──────────────────────────────────────────────────────');

          if (response.data['code'] == 401) {
            Storage.clearToken();
            Storage.remove('user_info');
            // 使用全局导航键安全跳转
            WidgetsBinding.instance.addPostFrameCallback((_) {
              try {
                if (_navigatorKey.currentState?.mounted ?? false) {
                  _navigatorKey.currentState?.pushNamed(AppRoutes.login);
                }
              } catch (e) {
                debugPrint('Navigation error: $e');
              }
            });
          }
          return handler.next(response);
        },
        onError: (DioException e, handler) {
          // 打印错误信息
          debugPrint('┌─────────────────────── Error ────────────────────────');
          debugPrint('│ URI: ${e.requestOptions.uri}');
          debugPrint('│ Error: ${e.error}');
          debugPrint('│ Response: ${e.response}');
          debugPrint('│ Message: ${e.message}');
          debugPrint('└──────────────────────────────────────────────────────');

          return handler.next(e);
        },
      ),
    );
  }

  static Future<Response> post(String path, dynamic data) async {
    return _dio.post(path, data: data);
  }
}
